package com.shiwaixiangcun.customer.module.intelligent

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v4.view.PagerAdapter
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.lechange.opensdk.api.bean.ShareDeviceList
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.Response
import com.shiwaixiangcun.customer.ConfigSps
import com.shiwaixiangcun.customer.GlobalApi
import com.shiwaixiangcun.customer.GlobalConfig
import com.shiwaixiangcun.customer.R
import com.shiwaixiangcun.customer.base.BaseActivity
import com.shiwaixiangcun.customer.entity.*
import com.shiwaixiangcun.customer.event.EventUtil
import com.shiwaixiangcun.customer.event.SimpleEvent
import com.shiwaixiangcun.customer.glide.ImageDisplayUtil
import com.shiwaixiangcun.customer.interfaces.OnViewpagerClickListenner
import com.shiwaixiangcun.customer.module.intelligent.camerautil.Business
import com.shiwaixiangcun.customer.module.intelligent.camerautil.Business.StringToAbility
import com.shiwaixiangcun.customer.module.intelligent.camerautil.entity.ChannelInfo
import com.shiwaixiangcun.customer.module.watch.BindWatchActivity
import com.shiwaixiangcun.customer.network.ResponseConfig
import com.shiwaixiangcun.customer.network.StringDialogCallBack
import com.shiwaixiangcun.customer.utils.AppSharePreferenceMgr
import com.shiwaixiangcun.customer.utils.JsonUtil
import com.tencent.smtt.sdk.*
import kotlinx.android.synthetic.main.activity_family_interaction.*
import kotlinx.android.synthetic.main.top_bar_white.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


/**
 * 亲情互动页面
 */
class FamilyInteractionActivity : BaseActivity(), View.OnClickListener {
    /**
     * 点击事件
     */
    override fun onClick(p0: View?) {

        when (p0) {
            layout_add_camera -> readyGo(AddSmartCameraActivity::class.java)
            layout_family_location -> readyGo(BindWatchActivity::class.java)
            back_left -> finish()
        }
    }

    var adapter: MyVpAdapter? = null
    var mList: ArrayList<ImageView>? = null
    var strToken: String? = null
    val REQUET_DATA = 1

    private var mChannelInfoList: MutableList<ChannelInfo>? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_family_interaction)
        EventUtil.getInstance().register(this)
        initData()
        initView()
    }

    override fun onPause() {
        super.onPause()
        EventUtil.getInstance().unregister(this)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun updateUI(simpleEvent: SimpleEvent) {
        when (simpleEvent.mEventType) {
            SimpleEvent.FAMILY_INTERACTION -> {
                when (simpleEvent.mEventValue) {
                    REQUET_DATA -> {
                        val familyInteraction = simpleEvent.data as FamilyInteraction
                        setCamera(familyInteraction.cameraInfo)
                        setWatchMap(familyInteraction.familyLocation)

                    }
                }
            }
        }


    }


    /**
     * 设置家人地图
     */
    private fun setWatchMap(familyLocation: String) {
        if (familyLocation.isEmpty()) {
            layout_family_location.visibility = View.VISIBLE
        } else {
            layout_family_location.visibility = View.GONE
            val url = familyLocation + "?access_token=" + strToken
            webView_location.clearCache(true)
            removeCookie(this)
            webView_location.webChromeClient = MyWebChromeViewClient()
            webView_location.webViewClient = MyWebViewClient()
            webView_location.loadUrl(url)
        }
    }

    /**
     * 清除Cookie
     *
     * @param context
     */
    private fun removeCookie(context: Context) {
        CookieSyncManager.createInstance(context)
        val cookieManager = CookieManager.getInstance()
        cookieManager.removeAllCookie()
        CookieSyncManager.getInstance().sync()
    }

    /**
     * 设置摄像头
     */
    private fun setCamera(cameraInfo: List<FamilyCameraInfo>) {

        if (cameraInfo.isEmpty()) {
            layout_add_camera.visibility = View.VISIBLE

        } else {
            layout_add_camera.visibility = View.GONE

            cameraInfo.map {
                Log.e(BUG_TAG, it.name)
                val iv = ImageView(this)
                iv.scaleType = ImageView.ScaleType.FIT_XY
                if (it.data.channels[0].channelPicUrl.isEmpty()) {
                    iv.setImageResource(R.drawable.bg_on_watch)
                } else {
                    ImageDisplayUtil.showImageView(mContext, it.data.channels[0].channelPicUrl, iv)

                }

                mList?.add(iv)
                mChannelInfoList?.addAll(devicesElementToResult(it.data, null))
                adapter?.addChannelData(mChannelInfoList)
                Business.getInstance().channelInfoList = mChannelInfoList
            }

            adapter?.notifyDataSetChanged()
        }
    }

    override fun onDestroy() {
        if (webView_location != null) {
            webView_location.loadDataWithBaseURL(null, "", "text/html", "utf-8", null)
            webView_location.clearHistory()

            (webView_location.parent as ViewGroup).removeView(webView_location)
            webView_location.destroy()
        }
        super.onDestroy()
    }
    /**
     * 请求智能设备数据
     */
    private fun initData() {


        mList = ArrayList()
        mChannelInfoList = ArrayList()
        strToken = AppSharePreferenceMgr.get(this, GlobalConfig.TOKEN, "") as String
        OkGo.get<String>(GlobalApi.familyInteraction)
                .params("access_token", strToken)
                .execute(object : StringDialogCallBack(this) {
                    override fun onError(response: Response<String>?) {
                        super.onError(response)
                        EventUtil.getInstance().post(SimpleEvent(SimpleEvent.FAMILY_INTERACTION, 2, false))
                    }
                    override fun onSuccess(response: Response<String>?) {
                        val type = object : TypeToken<DeviceBaseEntity<FamilyInteraction>>() {}.type
                        val fromJson = Gson().fromJson<DeviceBaseEntity<FamilyInteraction>>(response?.body(), type)
                        when (fromJson.responseCode) {
                            ResponseConfig.SUCCESS -> {
                                EventUtil.getInstance().postSticky(SimpleEvent(SimpleEvent.FAMILY_INTERACTION, REQUET_DATA, fromJson.data))
                            }
                        }
                    }
                })

        initCameraToken()


    }

    private fun initView() {
        mChannelInfoList = ArrayList()
        tv_top_right.text = "我的设备"
        tv_page_name.text = "亲情互动"
        layout_scroll.smoothScrollTo(0, 0)
        tv_top_right.visibility = View.VISIBLE
        tv_top_right.setOnClickListener { readyGo(IntelligentDeviceActivity::class.java) }

        back_left.setOnClickListener(this)
        layout_add_camera.setOnClickListener(this)
        layout_family_location.setOnClickListener(this)
        mList = ArrayList()
        adapter = MyVpAdapter(mList!!)
        adapter?.setOnItemClick(OnViewpagerClickListenner { position, _ ->
            val intent = Intent(mContext, MediaPlayActivity::class.java)
            intent.putExtra("UUID", adapter?.mChanelList!![position].uuid)

            startActivity(intent)
        })
        vp_camera.pageMargin = 40
        vp_camera.adapter = adapter


    }


    /**
     * 摄像头 Adapter
     */
    inner class MyVpAdapter(private val pageList: List<ImageView>) : PagerAdapter() {

        var mChanelList: MutableList<ChannelInfo>? = null

        init {
            mChanelList = ArrayList()
        }

        override fun getCount(): Int {
            return pageList.size
        }

        override fun isViewFromObject(arg0: View, arg1: Any): Boolean {
            return arg0 === arg1
        }

        private var mListener: OnViewpagerClickListenner? = null

        fun setOnItemClick(listener: OnViewpagerClickListenner) {
            this.mListener = listener
        }

        override fun instantiateItem(container: ViewGroup, position: Int): Any {
            container.addView(pageList[position])
            pageList[position].setOnClickListener {
                mListener?.onItemClick(position, pageList[position])
            }
            return pageList[position]
        }

        override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {

            container.removeView(pageList[position])
        }

        fun addChannelData(mChannelInfoList: MutableList<ChannelInfo>?) {
            mChanelList = mChannelInfoList
        }
    }


    /**
     *获取摄像头通道
     */
    private fun devicesElementToResult(devElement: CameraData,
                                       shareDevElement: ShareDeviceList.ResponseData.DevicesElement?): List<ChannelInfo> {

        val channelList = java.util.ArrayList<ChannelInfo>()

        // 解析绑定通道列表
        if (devElement.channels != null) {
            for (chnlElement in devElement.channels) {
                val chnlInfo = ChannelInfo()
                chnlInfo.deviceCode = devElement.deviceId
                chnlInfo.deviceModel = devElement.deviceModel
                chnlInfo.encryptMode = 0
                chnlInfo.index = chnlElement.channelId
                chnlInfo.name = chnlElement.channelName
                chnlInfo.backgroudImgURL = chnlElement.channelPicUrl
                chnlInfo.cloudMealStates = chnlElement.csStatus
                chnlInfo.alarmStatus = chnlElement.alarmStatus

                if (devElement.ability.contains("HSEncrypt")) {
                    chnlInfo.encrypt = 1
                } else {
                    chnlInfo.encrypt = 0
                }
                // 设置设备能力集
                chnlInfo.ability = StringToAbility(devElement.ability)

                // 设备与通道同时在线，通道才算在线
                if (chnlElement.channelOnline) {
                    when (devElement.status) {
                        "0" -> {
                            chnlInfo.state = ChannelInfo.ChannelState.Offline
                        }
                        "1" -> chnlInfo.state = ChannelInfo.ChannelState.Online
                        "3" -> chnlInfo.state = ChannelInfo.ChannelState.Upgrade
                    }
                }
                channelList.add(chnlInfo)
            }
        }

        // 解析分享设备通道列表
        if (shareDevElement != null && shareDevElement.channels != null) {
            for (chnlElement in shareDevElement.channels) {
                val chnlInfo = ChannelInfo()
                chnlInfo.deviceCode = shareDevElement.deviceId
                chnlInfo.deviceModel = shareDevElement.deviceModel
                chnlInfo.encryptMode = shareDevElement.encryptMode
                chnlInfo.index = chnlElement.channelId
                chnlInfo.name = chnlElement.channelName + "[shared]"
                chnlInfo.backgroudImgURL = chnlElement.channelPicUrl
                chnlInfo.alarmStatus = chnlElement.alarmStatus

                if (shareDevElement.ability.contains("HSEncrypt")) {
                    chnlInfo.encrypt = 1
                } else {
                    chnlInfo.encrypt = 0
                }
                // 设置设备能力集
                chnlInfo.ability = StringToAbility(shareDevElement.ability)

                // 设备与通道同时在线，通道才算在线
                if (chnlElement.channelOnline)
                    when (shareDevElement.status) {
                        0 -> chnlInfo.state = ChannelInfo.ChannelState.Offline
                        1 -> chnlInfo.state = ChannelInfo.ChannelState.Online
                        3 -> chnlInfo.state = ChannelInfo.ChannelState.Upgrade
                    }
                channelList.add(chnlInfo)
            }
        }
        return channelList
    }


    /**
     * WebView  加载进度显示
     */
    private inner class MyWebChromeViewClient : WebChromeClient() {

        override fun onProgressChanged(view: WebView, newProgress: Int) {
            if (newProgress == 100) {
                myProgressBar.visibility = View.GONE
            } else {
                if (View.INVISIBLE == myProgressBar.visibility) {
                    myProgressBar.visibility = View.VISIBLE
                }
                myProgressBar.progress = newProgress
            }
            super.onProgressChanged(view, newProgress)
        }


    }

    /**
     * 处理通知 ，请求事件
     */
    private inner class MyWebViewClient : WebViewClient() {
        override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
            view.loadUrl(url)
            return true
        }
    }


    /**
     * 初始化用户摄像头处理的Token
     */
    private fun initCameraToken() {
        val strToken = AppSharePreferenceMgr.get(mContext, ConfigSps.CURRENT_TOKEN, "") as String
        OkGo.get<String>(GlobalApi.cameraToken)
                .params("access_token", strToken)
                .execute(object : StringCallback() {
                    override fun onSuccess(response: Response<String>?) {
                        val type = object : TypeToken<DeviceBaseEntity<CameraToken>>() {}.type
                        val fromJson = JsonUtil.fromJson<DeviceBaseEntity<CameraToken>>(response?.body(), type)
                        when (fromJson.responseCode) {
                            ResponseConfig.SUCCESS -> {
                                Business.getInstance().token = fromJson.data.verificationCamera
                            }
                        }
                    }

                })
    }


}
